package com.sziit.se.highconcurrency.common.security;

import com.sziit.se.highconcurrency.common.annotation.CurrentUser;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import java.util.Objects;

public class CurrentUserResolver implements HandlerMethodArgumentResolver {

    /**
     * 配置支持转换的参数类型
     *
     * @param parameter 参数
     * @return 是否支持
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class) && parameter.getParameterType().isAssignableFrom(CurrentUserInfo.class);
    }


    /**
     * 解析函数
     *
     * @param p             包装后的参数
     * @param mavContainer  上下文容器
     * @param webRequest    请求体
     * @param binderFactory {@link WebDataBinder}实例的创建工厂
     * @return 解析后的结果
     * @throws MissingServletRequestPartException 可能抛出的异常
     */
    @Override
    public Object resolveArgument(MethodParameter p, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws MissingServletRequestPartException {
        CurrentUserInfo currentUserInfo = (CurrentUserInfo) webRequest.getAttribute("CurrentUserInfo", NativeWebRequest.SCOPE_REQUEST);
        if (Objects.isNull(currentUserInfo)) {
            throw new MissingServletRequestPartException("获取当前用户信息失败");
        }
        return currentUserInfo;
    }
}